<template>
  <div class="container">
    <div class="content">
      <el-page-header @back="goBack" content="角色和权限设置"></el-page-header>
      <div>
        <el-container class="main" style="border: 1px solid #eee">
          <el-aside width="300px" style="background-color: rgb(238, 241, 246)">
            <div class="peopleList">
              <el-menu>
                <div class="roleHead">
                  <div class="left">
                    <i class="el-icon-office-building"></i>
                    <span>角色</span>
                  </div>
                  <div class="right">
                    <i class="el-icon-plus " @click="addpermission" v-show="utils.checkAdminPermission('系统设置.角色和权限.管理')"></i>
                  </div>
                  <!-- 弹出层 -->

                  <el-dialog :title="(roleType?'编辑':'新建')+'角色'" :visible.sync="dialogVisible2" width="500px">
                    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                      class="demo-ruleForm">
                      <el-form-item label="角色名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                      </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible2 = false">取 消</el-button>
                      <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
                    </span>
                  </el-dialog>

                </div>
                <div class="bigItem">
                  <el-menu-item class="menuItem" v-for="(item,index) in roleList " :key='index'
                    @click="roleItem(item,index)">
                    <span :class="{'active':clickNumber == index}">{{item.name}}</span>
                    <i class="el-icon-delete" @click="deletePermission(item.id)" v-if="item.name !='超级管理员' &&  utils.checkAdminPermission('系统设置.角色和权限.管理')"></i>
                    <i class="el-icon-edit" @click="edit(item)" v-if="item.name !='超级管理员' && utils.checkAdminPermission('系统设置.角色和权限.管理')"></i>
                  </el-menu-item>
                </div>
              </el-menu>
            </div>
          </el-aside>
          <el-main>
            <div class="middle" v-if="clickNumber == index" v-for="(item,index) in roleList " :key='index'>
              <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
                <el-tab-pane label="角色权限" name="角色权限">
                  <div class="tab-main">
                    <el-tabs v-model="activeName2" @tab-click="handleClick2">
                      <el-tab-pane :label="i.name" :name="i.name" v-for="(i,k) in Permission" :key="k">
                        <div class="itemOne" v-for="(u, g) in i.peritem" :key="g">
                          <div class="status">
                            {{u.name}}
                          </div>
                          <div class="group">
                            <!-- 这里要取反，因为有权限就true，ture就禁止了 -->
                            <el-checkbox :label="o.id" v-for="(o,m) in u.children" :disabled="isdefault && utils.checkAdminPermission('系统设置.角色和权限.管理')"
                              @change="checkBox2($event,o)" :key="m" :checked="o.checked">{{o.name}}</el-checkbox>
                          </div>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="人员操作" name="人员操作">
                  <div class="tab-p">
                    <el-row type="flex" justify="space-between" class="nav-bar">
                      <el-col :span="3" v-show="utils.checkAdminPermission('系统设置.角色和权限.管理')">
                        <el-button type="primary" @click="create">新建</el-button>
                      </el-col>
                      <el-col class="text-right">
                        <el-form :inline="true" label-width="auto" class="nav-bar-form">
                          <el-form-item>
                            <el-input placeholder="关键词搜索" v-model="key" clearable prefix-icon="el-icon-search"
                              @clear="getList"></el-input>
                          </el-form-item>
                          <el-form-item>
                            <el-button type="primary" @click="getList">查询</el-button>
                          </el-form-item>
                        </el-form>
                      </el-col>
                    </el-row>

                    <!-- 列表 -->
                    <el-table :data="adminPeople" style="width: 100%" stripe>
                      <el-table-column type="selection" width="55">
                      </el-table-column>
                      <el-table-column prop="name" label="管理员名称">
                      </el-table-column>
                      <el-table-column prop="sysroles" label="角色" width="150">
                        <template slot-scope="scope">
                          <span>{{scope.row.rolename}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="state" label="状态" width="150">
                        <template slot-scope="scope">
                          <span class="color-success" v-if="scope.row.state == '已启用'">{{scope.row.state}}</span>
                          <span class="color-danger" v-if="scope.row.state == '已冻结'">{{scope.row.state}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" fixed="right" width="180">
                        <template slot-scope="scope" >
                          <!-- 	<el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button> -->
                          <!-- <el-button @click="create(scope.row)" type="text" size="small">修改</el-button> -->
                          <el-button @click="remove(scope.row.id)" type="text" size="small" v-show="utils.checkAdminPermission('系统设置.角色和权限.管理')">移除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <!-- 分页 -->
                  <div class="table-pagination">
                    <el-pagination background layout="sizes, total, prev, pager, next" :total="total"
                      :page-sizes="[10, 50, 100, 200]" :page-size="pageSize" :current-page="page"
                      @current-change="pageChange" @size-change="handleSizeChange">
                    </el-pagination>
                  </div>

                  <el-dialog title="新建管理员" :visible.sync="dialogVisible" width="800px">
                    <el-table :data="addList" style="width: 100%" stripe @selection-change="seleChange">
                      <el-table-column type="selection" width="55">
                      </el-table-column>
                      <el-table-column prop="name" label="管理员名称">
                      </el-table-column>
                      <el-table-column prop="sysroles" label="角色" width="150">
                        <template slot-scope="scope">
                          <span>{{scope.row.rolename}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="state" label="状态" width="150">
                        <template slot-scope="scope">
                          <span class="color-success" v-if="scope.row.state == '已启用'">{{scope.row.state}}</span>
                          <span class="color-danger" v-if="scope.row.state == '已冻结'">{{scope.row.state}}</span>
                        </template>
                      </el-table-column>
                    </el-table>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible = false">取 消</el-button>
                      <el-button type="primary" @click="addAdmin">确 定</el-button>
                    </span>
                  </el-dialog>



                  <!-- <div class="itemTwo">
                      <div class="status">
                          操作人员
                      </div>
                      <el-checkbox-group v-model="checkListPeople" class="group">
                        <el-checkbox :label="item.name" v-for="(item,index) in adminPeople " :key='index'></el-checkbox>
                      </el-checkbox-group>
                  </div> -->
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-main>
        </el-container>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    layout: 'admin',
    head() {
      return {
          title:'角色和权限设置-' + this.websetting.name
      }
    },
    data() {
      return {
        //表单
        ruleForm: {
          name: '',
          id: 0,
        },
        rules: {
          name: [{
              required: true,
              message: '请输入活动名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 12,
              message: '长度在 2 到 12 个字符',
              trigger: 'blur'
            }
          ]
        },
        page: 1,
        pageSize: 10,
        total: 0, //页码
        key: '',
        clickItem: '',
        roleList: [],
        clickNumber: 0,
        activeName: '角色权限',
        activeName2: '客户组列表',
        Permission: [],
        checkList: [],
        checkListPeople: [],
        adminPeople: [],
        dialogVisible: false,
        dialogVisible2: false,
        roleId: 0, //普通管理员
        addList: [], //新建列表名单
        addPeopleId: [],
        powersId: ',',
        box2: '',
        checked: false, //这个是判定当前的复选框的状态
        isCheckedId: '', //这个是拿管理员已经有的权限
        isdefault: false, //人员权限
        roleType: false,
        loading: false
      }
    },
    mounted() {
      this.getRole()
      this.getAdminList()
      this.addAdminList()
      // this.getPermission()
    },
    methods: {
      // 编辑
      edit(obj) {
        this.roleType = true;
        this.ruleForm = obj;
        this.dialogVisible2 = true;
      },
      // 删除角色
      deletePermission(id) {
        this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post('/Role/Delete?id=' + id).then((res) => {
            this.getRole()
          })
        }).catch(() => {

        });
      },
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var url = '/Role/Create';
            if (this.roleType == true) {
              url = '/Role/edit';
            } else {
              this.ruleForm.id = 0;
            }
            this.$axios.post(url, this.ruleForm).then((res) => {
              this.dialogVisible2 = false,
                this.getRole()
              this.$message({
                message: res.msg,
                type: 'success'
              });
            })
          } else {
            return false;
          }
        });
      },
      addpermission() {
        this.roleType = false;
        this.dialogVisible2 = true;
        this.ruleForm = {
          id: 0,
          name: ''
        };
      },
      checkBox2(event, o) {
        this.loading = true
        if (event) {
          // console.log(this.roleId)
          this.$axios.get('/OperationPermission/Add?id=' + this.roleId + '&PermissionId=' + o.id).then((res) => {
            o.checked = true
            this.loading = false
          })
        } else {
          // console.log(this.roleId)
          this.$axios.get('/OperationPermission/Delete?id=' + this.roleId + '&PermissionId=' + o.id).then((res) => {
            o.checked = false
            this.loading = false
          })
        }
        // 再拿一次
        // this.getRole()
      },
      // checkBox(val){
      //   console.log(val)
      //   this.powersId=val.join(',')
      // },
      seleChange(val) {
        this.addPeopleId = []
        let id = val.map((item) => {
          this.addPeopleId.push(item.id)
        })
        this.addPeopleId = this.addPeopleId.join(',')
      },
      //添加
      addAdmin() {
        this.$axios.get('/OperationPermission/SetAdminsRole?Id=' + this.roleId + '&Ids=' + this.addPeopleId).then((
          res) => {
            this.$message.success(res.msg);
            this.dialogVisible = false
            this.getAdminList()
          })
      },
      // 移除
      remove(id) {
        this.$confirm('此操作将删除该管理员, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.get('/OperationPermission/SetAdminsRole?id=-1&Ids=' + id).then((res) => {
            this.$message.success(res.msg);
            this.getAdminList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      pageChange(e) { // 页码切换事件
        this.page = e;
        this.getAdminList()
      },
      handleSizeChange(val) {
        this.page = 1;
        this.pageSize = val;
        this.getAdminList()
      },
      getList() {
        this.getAdminList()
      },
      create() {
        this.dialogVisible = true
        this.addAdminList()
      },
      addAdminList() {
        this.$axios.post('/role/AdminList', {
          "pageIndex": this.page,
          "pageSize": this.pageSize,
          "key": this.key,
          "typeId": 0, //管理员身份，超级还是普通
          "order": [{
            "column": "id",
            "isDesc": true
          }],
          "state": 0
        }).then((res) => {

          this.addList = res.rows

        })
      },
      // 请求管理员名单
      getAdminList() {
        this.$axios.post('/role/AdminList', {
          "pageIndex": this.page,
          "pageSize": this.pageSize,
          "key": this.key,
          "typeId": this.roleId, //管理员身份，超级还是普通
          "order": [{
            "column": "id",
            "isDesc": true
          }],
          "state": 0
        }).then((res) => {
          this.adminPeople = res.rows
        })
      },

      handleClick(tab, event) {

      },
      handleClick2(tab, event) {

      },
      // 管理员身份切换
      roleItem(item, index) {
        this.Permission = []
        this.isCheckedId = item.operationpermission
        this.roleId = item.id
        this.isdefault = item.isdefault
        this.clickNumber = index
        this.getAdminList()
        this.updataRolePermission()
      },
      goBack() {
        this.$router.go(-1)
      },
      // 角色id切换
      updataRolePermission() {
        this.$axios.get('/role/detail?id=' + this.roleId).then((res) => {
          this.isCheckedId = res.operationpermission.split(',')
          this.isCheckedId.forEach((res, index) => {
            if (res == "") {
              this.isCheckedId.splice(index, 1)
            }
          })

          // this.isCheckedId.pop()
          // this.isCheckedId.shift()
          this.getPermission()
        })
      },
      // 请求超级或者是普通
      getRole() {
        this.$axios.post('/Role/List', {
          "pageIndex": 1,
          "pageSize": 9,
          "offset": 0,
          "key": "",
          "typeId": 0,
          "order": [{
            "column": "id",
            "isDesc": true
          }],
          "state": 0
        }).then((res) => {
          this.roleList = res.rows
          this.roleId = this.roleList[0].id
          this.isCheckedId = this.roleList[0].operationpermission
          this.isCheckedId = this.isCheckedId.split(',')
          this.isCheckedId.pop()
          this.isCheckedId.shift()
          this.getPermission()
        })
      },

      getPermission() {

        this.$axios.get('/OperationPermission/GetAll').then((res) => {
          this.Permission = res

          //添加一个状态
          this.Permission.forEach((res) => {
            res.peritem.forEach((item) => {
              item.children.forEach((o) => {
                o.checked = false
                this.isCheckedId.forEach((i) => {
                  if (i == o.id) {
                    o.checked = true
                  } else {
                    return
                  }
                })
              })
            })
          })
          //  console.log(this.Permission)
          // console.log(this.isCheckedId)
        })
      },
    }
  }
</script>

<style lang="scss" scoped="scoped">
  .content {

    .main {
      margin-top: 20px;
      height: calc(100vh - 200px);

      .peopleList {
        .roleHead {
          padding: 10px;
          padding-right: 25px;
          background-color: rgb(238, 241, 246);
          display: flex;
          align-items: center;
          justify-content: space-between;

          .left {
            display: flex;
            align-items: center;

            i {
              font-size: 25px;
            }

            span {
              margin-left: 5px;
            }
          }

          .right {
            display: flex;
            justify-content: space-between;

            i {
              font-size: 18px;
              font-weight: bolder;
            }
          }
        }

        .bigItem {
          // overflow-y: auto;
          height: 100%;

          .menuItem {
            border-bottom: 1px solid var(--light);
            color: black;

            span {
              padding-left: 20px;
            }

            i {
              float: right;
              margin-top: 25px;
              font-weight: bold;
              font-size: 16px;
            }

            .active {
              color: var(--blue);
              border-left: 3px solid var(--blue);
            }
          }
        }
      }

      .middle {
        width: 100%;
        height: 100%;

        .tab-main {
          min-height: calc(100vh - 375px);
        }

        .tab-p {
          min-height: calc(100vh - 375px);
        }

        .itemOne {
          margin-top: 20px;

          &:nth-child(1) {
            margin-top: 0px;
          }

          .group {
            padding: 20px;
            border: 1px solid var(--light);
          }

          .status {
            padding: 10px;
            // border-bottom: 1px solid lightgrey;
            background-color: #eef1f6;
          }
        }

        .itemTwo {
          .group {
            margin-top: 20px;
            background-color: #eef1f6;
            padding: 20px;
            margin-top: 5px;
          }

          .status {
            padding: 10px;
            border-bottom: 1px solid var(--light);
          }
        }
      }
    }
  }
</style>
